# _*_ coding: utf-8 _*_
from odoo import models, fields, _
from odoo.exceptions import Warning


class AssignPurchaseRequisitionLine(models.TransientModel):
    _name = "assign.purchase.requisition.line.wizard"

    user_id = fields.Many2one("res.users", string="User", required=True, default=lambda self: self.env["purchase.requisition.line"].browse(self.env.context.get("active_ids"))[0].product_id.categ_id.user_id)

    def action_ok(self):
        self.ensure_one()
        lines = self.env["purchase.requisition.line"].browse(self.env.context.get("active_ids"))
        if len(lines.mapped('product_id.categ_id.user_id')) > 1:
            raise Warning(u'只有相同品类负责人才允许进行合并分配')
        if 'assign' in lines.mapped('state'):
            raise Warning(_("Assign twice is not allowed."))
        for line in lines:
            if line.state != 'confirm':
                raise Warning(u'只有状态为确认时才允许进行分配')
            if line.requisition_id.state != 'open':
                raise Warning(u'只有请购单状态为请购核准时才允许进行分配')
        if lines:
            lines.write({
                "user_id": self.user_id.id,
                "state": "assign"
            })
